<?php

namespace App\Library\Logic;

use App\Library\Requests\Im\ImNewRequest;
use App\Library\Requests\Message\MessageNewRequest;
use App\Library\Requests\Message\MessagePageRequest;
use App\Models\MessageModel;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\DB;

class MessageLogic extends MessageModel
{
    /**
     * 分页
     * @param MessagePageRequest $request
     * @return array
     */
    public function paging(MessagePageRequest $request): array
    {
        $k = 'kf:' . USERID;
        $userId = cache()->has($k) ? cache($k)['sellerId'] : USERID;
        $builder = $this->newQuery()->where(function (Builder $builder) use ($request, $userId) {
            $builder->where(function (Builder $builder) use ($request, $userId) {
                $builder->where('send_id', $userId)->where('accept_id', $request->acceptId);
            })->orWhere(function (Builder $builder) use ($request, $userId) {
                $builder->where('send_id', $request->acceptId)->where('accept_id', $userId);
            });
        });
        if ($request->id > 0) $builder->where('id', '<', $request->id);
        return paginate($builder->orderByDesc('id')->paginate($request->limit, $this->columns($userId)));
    }

    /**
     * 最新
     * @param MessageNewRequest $request
     * @return Collection|array
     */
    public function new(MessageNewRequest $request): Collection|array
    {
        $k = 'kf:' . USERID;
        $userId = cache()->has($k) ? cache($k)['sellerId'] : USERID;
        return $this->newQuery()->where(function (Builder $builder) use ($request, $userId) {
            $builder->where(function (Builder $builder) use ($request, $userId) {
                $builder->where('send_id', $userId)->where('accept_id', $request->acceptId);
            })->orWhere(function (Builder $builder) use ($request, $userId) {
                $builder->where('send_id', $request->acceptId)->where('accept_id', $userId);
            });
        })->where('id', '>', $request->id)->orderByDesc('id')->get($this->columns($userId));
    }

    /**
     * columns
     * @param int $userId
     * @return array
     */
    private function columns(int $userId): array
    {
        return [
            'id',
            'kefu_id',
            'file_id',
            'content',
            'object_type',
            'object_id',
            'extend',
            'created_at',
            DB::raw('if(send_id=' . $userId . ',1,0) as my'),
        ];
    }
}
